<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" align="center" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :type="col.type"
                :sortable="col.sortable"
            >
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary" @click="onAdd"
            >保存</el-button
        >
    </el-button-group>
</template>
<script setup lang="ts" name="ActionsSelect">
import { ref, reactive, onMounted, ComputedRef } from 'vue';
import { ElTable } from 'element-plus';
// import { Plus } from '@element-plus/icons-vue';
import { isEmpty, forEach } from 'lodash';

import { ActionModel } from '@/common/types/model';
import { tableColumnDefault, tableDefaultAttribute } from '@/hooks/useTable';
import type { TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';

const props = defineProps<{
    menuId: number;
}>();
const emit = defineEmits<{
    close: []
}>();
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = reactive<Array<ActionModel>>([]);

const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'label',
        label: '功能名称',
        sortable: true,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'url',
        label: 'url',
        sortable: true,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'remark',
        label: '备注',
        sortable: false,
    },
]);
let tableHeight: ComputedRef;

const onRefresh = async () => {
    const req = new Request('未选功能查询', {
        menuId: props.menuId,
    });
    const r = await req.post();

    tableData.length = 0;
    // tableData.value = [];
    if (!isEmpty(r.obj)) {
        forEach(r.obj, (value) => {
            tableData.push(value);
        });
    }
};

onMounted(() => {
    onRefresh();
});


const onAdd = async () => {
    const rows = tableRef.value?.getSelectionRows();
    const ids = Array<{
        menu: {id: number} ,
        action: {id: number},
    }>();
    forEach(rows, (v: ActionModel) => {
        ids.push({ menu: {id: props.menuId}, action: {id: v.id as number}});
    });
    const req = new Request('菜单功能增加', ids);
    const r = await req.post();
    if (r.code > 100) {
        emit('close');
    }
};
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}
</style>
